package org.learnredis.dataReaders;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.learnredis.student.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class StudentReader {
    private static final Logger logger
            = LoggerFactory.getLogger(StudentReader.class);

    private StudentReader() {}

    public static ArrayList<Student> fileRead() throws IOException {

        ArrayList studentList = new ArrayList<Student>();
        
        try {
            String filePath = StudentReader.class.getResource("/universityInfo.xlsx").getPath();

            logger.info(String.format("Get file in path: %s", filePath));

            FileInputStream file = new FileInputStream(new File(filePath));

            logger.info("File found");

            XSSFWorkbook workbook = new XSSFWorkbook(file);

            XSSFSheet studentPage = workbook.getSheetAt(0);

            logger.info("Read student page");

            Iterator<Row> rowStudentIterator = studentPage.iterator();

            if (rowStudentIterator.hasNext()) rowStudentIterator.next();

            while (rowStudentIterator.hasNext()) {
                Iterator<Cell> cellIterator = rowStudentIterator.next().cellIterator();

                Student student = new Student();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    int index = cell.getColumnIndex();

                    switch (index) {
                        case 0:
                            student.setUniversityId(cell.getStringCellValue());
                            break;
                        case 1:
                            student.setFullName(cell.getStringCellValue());
                            break;
                        case 2:
                            student.setCurrentCourseNumber((int) cell.getNumericCellValue());
                            break;
                        case 3:
                            student.setAvgExamScore((float) cell.getNumericCellValue());
                            break;
                        default:
                            logger.debug("Cell Student not value");
                    }
                }
                studentList.add(student);
            }

        } catch (FileNotFoundException e) {
            logger.error("File not found");
        } catch (IOException e) {
            System.out.println("IO Exception: " + e.getMessage());
            logger.error("Error read file",e);
        }

        return studentList;
    }
}

